package com.esint;

import redis.clients.jedis.Jedis;

import java.util.concurrent.TimeUnit;

/**
 * @description: redis String类型测试类
 * @author: 谷明
 * @createDate: 2021/8/12 0:02
 */
public class TestString {


    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.43.166", 6379);
        jedis.flushDB();
        System.out.println("======================增加数据======================");
        System.out.println(jedis.set("key1", "value1"));
        System.out.println(jedis.set("key2", "value2"));
        System.out.println(jedis.set("key3", "value3"));
        System.out.println("删除键key2：" + jedis.del("key2"));
        System.out.println("获取键key2：" + jedis.get("key2"));
        System.out.println("修改key1：" + jedis.set("key1", "value1Changed"));
        System.out.println("获取key1的值：" + jedis.get("key1"));
        System.out.println("在key3后面追加值：" + jedis.append("key3", "TheAppendPart"));
        System.out.println("key3的值：" + jedis.get("key3"));
        System.out.println("增加多个键值对：" + jedis.mset("key01", "value01", "key02", "value02", "key03", "value03", "key04", "value04"));
        System.out.println("获取多个键值对：" + jedis.mget("key01", "key02", "key03", "key04"));
        System.out.println("删除多个键值对：" + jedis.mget("key01", "key02"));
        System.out.println("获取多个键值对：" + jedis.mget("key01", "key02", "key03", "key04"));

        jedis.flushDB();
        System.out.println("======================新增键值对防止覆盖原先值======================");
        System.out.println("设置key1：" + jedis.setnx("key1", "value1"));
        System.out.println("设置key2：" + jedis.setnx("key2", "value2"));
        System.out.println("再次设置key2：" + jedis.setnx("key2", "value2-changed"));
        System.out.println("获取key1：" + jedis.get("key1"));
        System.out.println("获取key2：" + jedis.get("key2"));

        System.out.println("======================新增键值并设置有效时间======================");
        System.out.println("设置key3过期时间为2秒：" + jedis.setex("key3", 2, "value3"));
        System.out.println("立即获取key3：" + jedis.get("key3"));
        //等待3秒再获取key3
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("三秒后获取key3："+jedis.get("key3"));

        System.out.println("======================获取原来的值，更新为新值======================");
        System.out.println("获取并更新key2："+jedis.getSet("key2", "MyNewKey2Value"));
        System.out.println("再次获取key2，应该获取到更新的值："+jedis.get("key2"));

        //字符串处理，类似substring
        System.out.println("获取key2局部值"+jedis.getrange("key2", 2, 5));
    }
}
